// ======================================================================================
//  File:		UniversalEntity.cs
//  Summary:	This sample provides a "Universal" CRM Business Entity that a 
//              standard .NET Data Grid can understand. This class implements 
//              ICustomTypeScriptor so that the class can describe itself to the data grid.
// ======================================================================================
//
//  This file is part of the Microsoft CRM 4.0 SDK Code Samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//
// =======================================================================================

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Metadata;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.SdkTypeProxy.Metadata;


namespace Streamsol.Crm.XrmDevelopmentToolkit
{
    /// <summary>
	/// Provides a "Universal" CRM Business Entity that a standard .NET Data Grid can understand.
	/// This class implements ICustomTypeScriptor so that the class can describe itself to the data grid.
	/// </summary>
	public class UniversalEntity : BusinessEntity, ICustomTypeDescriptor
	{
		private PropertyDescriptorCollection _propertyDescriptors;
		private IDictionary _properties;

		public UniversalEntity(PropertyDescriptorCollection propertyDescriptors, IDictionary propertyValues)
		{
			_propertyDescriptors = propertyDescriptors;
			_properties = propertyValues;
		}

		/// <summary>
		/// Creates a collection of PropertyDescriptors from an array of CRM attributes
		/// </summary>
		public static PropertyDescriptorCollection CreatePropertyDescriptorCollection(AttributeMetadata[] attributes)
		{
			LocalPropertyDescriptor[] pds = new LocalPropertyDescriptor[attributes.Length];
	
			int npd = 0;

			// Populate the Property Descriptor collection with Propery descriptors
			foreach (AttributeMetadata d in attributes)
			{
				Type tmp;
				
				if (d is DateTimeAttributeMetadata)
				{
					tmp = typeof(System.DateTime);
				}
				else
				{
					tmp = typeof(string);
				}
	
				pds[npd] = new LocalPropertyDescriptor(d.LogicalName, tmp);
				npd++;
			}

			return new PropertyDescriptorCollection(pds);
		}

		/// <summary>
		/// Create a new Universal Entity from a Dynamic CRM Entity
		/// </summary>
		public static UniversalEntity CreateFromDynamicEntity(DynamicEntity entity, 
            PropertyDescriptorCollection propertyDescriptors)
		{
			IDictionary properties = new HybridDictionary(entity.Properties.Count, false);

			// Populate the dictionary with name-value pairs of the
			// entities properties and that properties respective data
			foreach (Property prop in entity.Properties)
			{
				// Use the default GetPropertyValue method to get the approriate value
				properties[prop.Name] = GetPropertyValue(prop);

				// For some property types, we want to support binding "additional data" to the grid.
				// For example a "Lookup Property" will generally have 3 main aspects to it:
				// - The ID (GUID) of the linked entity
				// - The display name of the link entity
				// - The type of the linked entity (Such as account or contact)
				//
				// The job of this code is to expand those additional properties out from the complex
				// CRM types and flatten them out in a predictable manner, so that they can be displayed
				// in a grid easily.
				// 
				// For this sample, all lookup properties will always have an addition field
				// named: Field Name + "name" and that field will contain the display name.
				// The base field under just "Field Name" will hold the ID.
				//
				// For example:
				// createdby		- would equal: {SOMEGUID}
				// createdbyname	- would equal: Some User's Name
				//
				Type propertyType = prop.GetType();

				if (propertyType == typeof(LookupProperty))
				{
					properties.Add(prop.Name + "name", ((LookupProperty)prop).Value.name);
				}

				// TODO: Add additional specific type handling as required
			}

			return new UniversalEntity(propertyDescriptors, properties);
		}

		/// <summary>
		/// Get the "value" of a property
		/// Based on the type of property, this method determines how to get the properties "value"
		/// With the exception of dates, this implementation  returns a user viewable string as the 
		/// value.  
		/// </summary>
		protected static object GetPropertyValue(Property prop)
		{
			// Based on the property type, we will determine what data should be returned to the 
			// Grid for display.  This sample includes some hard-coded default behavior that may
			// or may not be approriate for your needs.

			Type propertyType = prop.GetType();

			if (propertyType == typeof(StringProperty))
			{
				return ((StringProperty)prop).Value;
			}
			else if (propertyType == typeof(CrmDateTimeProperty))
			{
				// Convert the CRM date into a System.DateTime
				string dateTimeAsText = (((CrmDateTimeProperty)prop).Value).Value;
				return DateTime.Parse(dateTimeAsText, CultureInfo.InvariantCulture, 
                    DateTimeStyles.AdjustToUniversal);
			}
			else if (propertyType == typeof(KeyProperty))
			{
				return ((KeyProperty)prop).Value.Value;
			}
			else if (propertyType == typeof(LookupProperty))
			{
				return (((LookupProperty)prop).Value).Value;
			}
			else if (propertyType == typeof(StateProperty))
			{
				return ((StateProperty)prop).Value;
			}
			else if (propertyType == typeof(PicklistProperty))
			{
				return ((PicklistProperty)prop).Value.name;
			}
			else if (propertyType == typeof(DynamicEntityArrayProperty))
			{
				// Not supported - There are only a few properties in CRM that should hit this
				// This sample does not implement this property type
				return "Array of child entities";
			}
            else if (propertyType == typeof(CrmMoneyProperty))
            {
                return (((CrmMoneyProperty)prop).Value).formattedvalue;
            }
            else if (propertyType == typeof(CrmBooleanProperty))
            {
                return (((CrmBooleanProperty)prop).Value).name;
            }

            else if (propertyType == typeof(StatusProperty))
            {
                return (((StatusProperty)prop).Value).name;
            }

            else if (propertyType == typeof(OwnerProperty))
            {
                return (((OwnerProperty)prop).Value).name;
            }

            else if (propertyType == typeof(CrmDecimalProperty))
            {
                return (((CrmDecimalProperty)prop).Value).formattedvalue;
            }
			// The property type is not supported
			return "Unsupported property type: " + propertyType.GetType().Name;
		}

		#region ICustomTypeDescriptor Members

		public TypeConverter GetConverter()
		{
			return null;
		}

		public EventDescriptorCollection GetEvents(Attribute[] attributes)
		{
			return null;
		}

		EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
		{
			return new EventDescriptorCollection(null);
		}

		public string GetComponentName()
		{
			return null;
		}

		public object GetPropertyOwner(PropertyDescriptor pd)
		{
			return this;
		}

		public AttributeCollection GetAttributes()
		{
			return new System.ComponentModel.AttributeCollection(null);
		}

		public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
		{
			return this._propertyDescriptors;
		}

		PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
		{
			return GetProperties(null);
		}

		public object GetEditor(Type editorBaseType)
		{
			return null;
		}

		public PropertyDescriptor GetDefaultProperty()
		{
			return null;
		}

		public EventDescriptor GetDefaultEvent()
		{
			return null;
		}

		public string GetClassName()
		{
			return null;
		}

		#endregion

		#region LocalPropertyDescriptor Class

		private class LocalPropertyDescriptor : PropertyDescriptor
		{
			private Type _valueType;

			public LocalPropertyDescriptor(string name, Type valueType)
				: base(name, null)
			{
				_valueType = valueType;
			}

			public override bool CanResetValue(object component)
			{
				return false;
			}

			public override object GetValue(object component)
			{
				return ((UniversalEntity)component)._properties[this.Name];
			}

			public override void ResetValue(object component)
			{
				throw new NotSupportedException();
			}

			public override void SetValue(object component, object value)
			{
				throw new NotSupportedException();
			}

			public override bool ShouldSerializeValue(object component)
			{
				return false;
			}

			public override Type ComponentType
			{
				get
				{
					return typeof(UniversalEntity);
				}
			}

			public override bool IsReadOnly
			{
				get
				{
					return true;
				}
			}

			public override Type PropertyType
			{
				get
				{
					return _valueType;
				}
			}
		}

		#endregion
	}
}